import signals
from django.core.exceptions import PermissionDenied

are_django_permissions_activated = False

def check_perm(model, user, type):
    #print u"checking %s on %s for %s" % (type, model.__name__, user)
    if not user.has_perm('%s.%s_%s' % (model._meta.app_label, type, model._meta.module_name) ):
        raise PermissionDenied(u'user %s does not have Permissions to %s %s' % (user, type, model.__name__) )
    else:
        return True

def check_update(sender, **kwargs):
    check_perm(kwargs['model'], kwargs['user'], 'change')

def check_create(sender, **kwargs):
    check_perm(kwargs['model'], kwargs['user'], 'add')

def check_delete(sender, **kwargs):
    check_perm(kwargs['model'], kwargs['user'], 'delete')

def check_show(sender, **kwargs):
    # since there is no default show permission in django
    # we just use the update permission, but if it fails
    # we also check for a 'show' permission
    errors = []
    try:
        check_perm(kwargs['model'], kwargs['user'], 'change')
    except PermissionDenied, e:
        # no change permission... but maybe show
        check_perm(kwargs['model'], kwargs['user'], 'show')
        


def activate_django_permissions():
    if not are_django_permissions_activated:
        signals.sc_model_pre_update.connect(check_update)
        signals.sc_model_pre_create.connect(check_create)
        signals.sc_model_pre_delete.connect(check_delete)
        signals.sc_model_pre_show.connect(check_show)
        signals.sc_model_pre_list.connect(check_show)